package com.hkbigdata.ontimer;

import com.hkbigdata.bean.WaterSensor;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author liuanbo
 * @creat 2024-05-21-17:55
 * @see 2194550857@qq.com
 */
public class Flink01_OnTimer_ProcessingTime {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> waterSensorSingleOutputStreamOperator = env.socketTextStream("hadoop102", 9999)
                .flatMap(new FlatMapFunction<String, WaterSensor>() {
                    @Override
                    public void flatMap(String value, Collector<WaterSensor> out) throws Exception {
                        String[] split = value.split(",");
                        out.collect(new WaterSensor(
                                split[0],
                                Long.valueOf(split[1]),
                                Double.valueOf(split[2])
                        ));
                    }
                });

        waterSensorSingleOutputStreamOperator.keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                        //注册一个基于处理的定时器
                        long time = ctx.timerService().currentProcessingTime();
                        ctx.timerService().registerProcessingTimeTimer(time + 5000L);
                        out.collect(value.toString());

                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                        //定时器执行之后可以做一些事儿
                        System.out.println("定时器执行时间" + timestamp);
                        System.out.println("定时器被执行了.....");
                    }
                }).print();

        env.execute();
    }
}
